package com.pro.grpcserver;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.logging.Level;
import java.util.logging.Logger;

@RestController
public class ProController {

    private static final Logger logger = Logger.getLogger(ProController.class.getName());

    @Value("${consul.ip}")
    private String consulIP;

    @ResponseBody
    @RequestMapping(path = "/pro", method = RequestMethod.POST)
    public String pro(@RequestParam(value = "param", required = true) String pro, HttpServletRequest request) {
        GrocServiceClientTwo client = null;
        try {
            client = new GrocServiceClientTwo(consulIP);
            GrocServiceClientTwoSingleton.getSignleton();
            String result = client.greet(pro);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            logger.log(Level.WARNING, "RPC failed: {0}", e.getMessage());
            return "{\"code\":-1,\"message\":"+e.getMessage()+"}";
        } finally {
            try {
                client.shutdown();
            } catch (InterruptedException e) {
                e.printStackTrace();
                logger.log(Level.WARNING, "RPC failed: {0}", e.getMessage());
                return "{\"code\":-1,\"message\":null}";
            }
        }
    }


    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}